package com.taplinker.app;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.taplinker.client.R;
import com.taplinker.client.core.LoginHistoryManager;
import com.taplinker.client.core.TaplinkerApplication;
import com.taplinker.client.domain.LoginUser;
import com.taplinker.client.im.rpc.LoginCmd;

public class LoginActivity extends Activity {
	private EditText nameEt;
	private EditText passwordEt;
	private CheckBox remenberCb;
	private CheckBox autoLoginCb;
	private Button loginBt;
	private View nameArea;
	private ImageView showUserHistory;
	private ProgressDialog dialog;
	private Handler handler;
	private Handler handlerLogin;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		TaplinkerApplication.getInstance().addActivity(this);
		setContentView(R.layout.login);

		findView();
		loadSetting();
		checkInput();
	}

	private void findView() {
		nameEt = (EditText) findViewById(R.id.name_et);
		passwordEt = (EditText) findViewById(R.id.password_et);
		remenberCb = (CheckBox) findViewById(R.id.remember_cb);
		autoLoginCb = (CheckBox) findViewById(R.id.auto_login_cb);
		loginBt = (Button) findViewById(R.id.login_bt);
		nameArea = findViewById(R.id.account_parent);
		showUserHistory = (ImageView) findViewById(R.id.show_more);
		loginBt.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				loginBt.setClickable(false);
				loginBt.setEnabled(false);
				hideKeyboard();
				loginDataCheck();
			}
		});
		remenberCb.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				remenberCb.setSelected(!remenberCb.isSelected());
				if (!remenberCb.isSelected()) {
					autoLoginCb.setSelected(false);
				}
			}
		});
		autoLoginCb.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				autoLoginCb.setSelected(!autoLoginCb.isSelected());
				if (autoLoginCb.isSelected()) {
					remenberCb.setSelected(true);
				}
			}
		});
		showUserHistory.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showUserHistory();
			}
		});
		View rootView = getWindow().getDecorView();
		if(rootView != null) {
			rootView.setOnTouchListener(new View.OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					hideKeyboard();
					return false;
				}
			});
		}
	}

	/**
	 * 输入校验
	 */
	private void checkInput() {
		nameEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable e) {
				if (e.length() < 1) {
					passwordEt.setText("");
					autoLoginCb.setSelected(false);
					remenberCb.setSelected(false);
				}
			}
		});
		passwordEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable e) {
				if (e.length() < 1) {
					autoLoginCb.setSelected(false);
					remenberCb.setSelected(false);
				}
			}
		});
	}

	public void showProgressDialog(CharSequence message) {
		if (dialog == null) {
			dialog = new ProgressDialog(this);
			dialog.setCanceledOnTouchOutside(false);
			dialog.setIndeterminate(true);
		}
		dialog.setMessage(message);
		dialog.show();
	}

	public void closeProgressDialog() {
		saveSetting();
		if (dialog != null && this.dialog.isShowing()) {
			dialog.dismiss();
		}
	}
	
	/**
	 * 保存登录设置
	 */
	private void saveSetting() {
		LoginUser user = new LoginUser();
		user.setName(nameEt.getText().toString().trim());
		user.setPassword(passwordEt.getText().toString().trim());
		user.setAutoLogin(autoLoginCb.isSelected());
		user.setRemember(remenberCb.isSelected());
		LoginHistoryManager.getInstance().save(this, user);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
				loginBt.setClickable(true);
				loginBt.setEnabled(true);
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 读取登录设置
	 */
	private void loadSetting() {
		handlerLogin = new InnerHandler() {
			
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				loginBt.setClickable(true);
				loginBt.setEnabled(true);
			}
		};
		LoginUser user = LoginHistoryManager.getInstance().getLast(this);
		if(user != null) {
			nameEt.setText(user.getName());
			passwordEt.setText(user.getPassword());
			autoLoginCb.setSelected(user.isAutoLogin());
			remenberCb.setSelected(user.isRemember());
			if(user.isAutoLogin()) {
				loginHandle();
			}
		} else {
			nameEt.setText("");
			passwordEt.setText("");
			autoLoginCb.setSelected(false);
			remenberCb.setSelected(false);
			showUserHistory.setVisibility(View.GONE);
		}
	}

	/**
	 * 输入合法检测
	 */
	private void loginDataCheck() {
		if (TextUtils.isEmpty(nameEt.getText().toString().trim())) {
			Toast.makeText(this, "用户名不能为空，请输入用户名", Toast.LENGTH_SHORT).show();
			handlerLogin.sendEmptyMessage(0);
			return;
		}
		if (TextUtils.isEmpty(passwordEt.getText().toString().trim())) {
			Toast.makeText(this, "密码不能为空，请输入密码", Toast.LENGTH_SHORT).show();
			handlerLogin.sendEmptyMessage(0);
			return;
		}
		loginHandle();
	}

	private void showUserHistory() {
		final List<LoginUser> list = LoginHistoryManager.getInstance().getAll(this);
		if(list != null && list.size() > 0) {
			final PopupWindow usersPopwin = new PopupWindow(this);
			ListView usersLv = (ListView) getLayoutInflater().inflate(R.layout.login_history_lv, null);
			usersLv.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					LoginUser user = list.get(position);
					nameEt.setText(user.getName());
					passwordEt.setText(user.getPassword());
					remenberCb.setSelected(user.isRemember());
					autoLoginCb.setSelected(user.isAutoLogin());
					usersPopwin.dismiss();
				}
			});
			handler = new InnerHandler() {
				
				@Override
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
					if(nameEt.getText().toString().trim().equals(msg.obj)) {
						loadSetting();
					}
					usersPopwin.dismiss();
				}
			};
			usersPopwin.setContentView(usersLv);
			usersLv.setAdapter(new LoginHistoryAdapter(this, list, handler));
			usersPopwin.setWindowLayoutMode(0, ViewGroup.LayoutParams.WRAP_CONTENT);
			usersPopwin.getBackground().setAlpha(200);
			Resources res = getResources();
			float width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 287, res.getDisplayMetrics());
			usersPopwin.setWidth((int) width);
			usersPopwin.setBackgroundDrawable(res.getDrawable(R.drawable.login_popo_bg));
			usersPopwin.setFocusable(true);
			usersPopwin.setTouchable(true);
			usersPopwin.showAsDropDown(nameArea, 2, 0);
		}

	}

	private void loginHandle() {
		String uName = nameEt.getText().toString().trim();
		String uPassword = passwordEt.getText().toString().trim();
		showProgressDialog("登陆中,请稍侯");
		new LoginCmd(uName, uPassword, this, handlerLogin).execute();
	}
	
	private void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if(imm != null && getCurrentFocus() != null){
			imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
	
	static class InnerHandler extends Handler {
	}

}